package com.xiangxiao.rpan.utils;

import java.io.File;
import java.io.FileInputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

/**
 * MD5加密工具类
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2022/12/29 17:08
 */
public class MD5Util {
  private MD5Util() {}

  private static final char[] HEX_DIGITS =
      {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

  public static String encode(File file) {
    try (FileInputStream in = new FileInputStream(file)) {
      FileChannel ch = in.getChannel();
      MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
      MessageDigest md5 = MessageDigest.getInstance("MD5");
      if (md5 != null) {
        md5.update(byteBuffer);
        return toHex(md5.digest());
      }
      return toHex(new byte[0]);
    } catch (Exception e) {
      System.out.println(e.toString());
      return null;
    }
  }

  public static String encode(String arg) {
    if (arg == null) {
      arg = "";
    }
    MessageDigest md5 = null;
    try {
      md5 = MessageDigest.getInstance("MD5");
      md5.update(arg.getBytes("UTF-8"));
    } catch (Exception e) {
      System.out.println(e.toString());
      return null;
    }
    return toHex(md5 != null ? md5.digest() : new byte[0]);
  }

  private static String toHex(byte[] bytes) {
    StringBuilder str = new StringBuilder(32);
    for (byte b : bytes) {
      str.append(HEX_DIGITS[(b & 0xf0) >> 4]);
      str.append(HEX_DIGITS[(b & 0x0f)]);
    }
    return str.toString();
  }
}
